package ar.unc.famaf.pln.giveselector.filters;

import java.util.*;

import ar.unc.famaf.pln.giveselector.context.*;

/**
 * A LexicalFilter filters out utterances containing wrong words.
 * @author Alexandre Denis
 */
public abstract class LexicalFilter implements IFilter
{
	protected String[] filteredWords;


	/**
	 * Creates a new LexicalFilter.
	 */
	public LexicalFilter(String... filteredWords)
	{
		this.filteredWords = filteredWords;
	}


	@Override
	public Set<Utterance> filter(Set<Utterance> utterances, Context context)
	{
		System.out.println(getClass().getSimpleName() + " Lexical Filter input: " + utterancesToString(utterances));
		Set<Utterance> utts = new HashSet<Utterance>(utterances);
		for(Iterator<Utterance> it = utts.iterator(); it.hasNext();)
			if (isFiltered(it.next()))
				it.remove();
		System.out.println(getClass().getSimpleName() + " Lexical Filter output: " + utterancesToString(utts));
		return utts;
	}


	/**
	 * Test if the given Utterance contains a forbidden lexical item.
	 */
	protected boolean isFiltered(Utterance utt)
	{
		String text = " " + utt.getText().toLowerCase() + " ";
		for(String forbiddenWord : filteredWords)
			if (text.indexOf(" " + forbiddenWord.toLowerCase() + " ") != -1)
				return true;
		return false;
	}


	/**
	 * Returns a String representation of the given Utterances.
	 * @param utterances
	 * @return
	 */
	protected static String utterancesToString(Set<Utterance> utterances)
	{
		StringBuilder ret = new StringBuilder();
		for(Utterance utt : utterances)
			ret.append(utt.getText() + " ; ");
		return ret.toString();
	}
}
